package metu.tespit.session.util;

/**
 * Created with IntelliJ IDEA.
 * User: ekisa
 * Date: 08.06.2012
 * Time: 09:26
 * To change this template use File | Settings | File Templates.
 */
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.TimeZone;

import metu.tespit.entitiy.accountManagement.User;
import metu.tespit.entity.course.Activity;
import metu.tespit.entity.course.ProjectTeam;
import metu.tespit.session.schedule.ActivityHome;

import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.annotations.async.Asynchronous;
import org.jboss.seam.annotations.async.Expiration;
import org.jboss.seam.annotations.async.IntervalCron;
import org.jboss.seam.async.QuartzTriggerHandle;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.faces.Renderer;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import javax.persistence.EntityManager;
import javax.persistence.TemporalType;

@Name("jobNotificationEmailsDueDateOver")
@AutoCreate
@Scope(ScopeType.APPLICATION)
public class JobNotificationEmailsDueDateOver {


    private User mailToUser;
    private Activity activity;
    private ProjectTeam projectTeam;

    @SuppressWarnings("unchecked")
	@Asynchronous
    public QuartzTriggerHandle createJobNotificationEmailsDueDateOver(
            @Expiration Date when, @IntervalCron String interval) {
        
    	EntityManager entityManager = (EntityManager) Component.getInstance("entityManager");
        Renderer renderer = (Renderer) Component.getInstance("org.jboss.seam.faces.renderer", true);
        ActivityHome activityHome = (ActivityHome) Component.getInstance("activityHome", true);
        
        DateTimeZone timeZone = DateTimeZone.forID("Europe/Istanbul");
		DateTime dateTime = new DateTime(timeZone);

        List<Activity> activitiesToBeWarned = (List<Activity>)entityManager.createQuery("from Activity a" +
                " where a.dueDate < :now and coalesce(a.dueDateOverEmailSent, false) = false").setParameter("now", dateTime.toDate(), TemporalType.TIMESTAMP)
                .getResultList();
        
        for (Iterator iterator = activitiesToBeWarned.iterator(); iterator.hasNext(); ) {
            try {
                activity = (Activity) iterator.next();

                List<ProjectTeam> projectTeams = activity.getSchedule().getCourse().getProjectTeams();
                for (Iterator<ProjectTeam> projectTeamIterator = projectTeams.iterator(); projectTeamIterator.hasNext(); ) {
                    projectTeam = projectTeamIterator.next();
                    for (Iterator<User> userIterator = projectTeam.getStudents().iterator(); userIterator.hasNext(); ) {
                        mailToUser = userIterator.next();
                        renderer.render("/Mail/notificationEmailDueDateOver.xhtml");
                    }
                }
                
                this.markActivityAsSent(activity, activityHome);
                
            } catch (Exception e) {
                e.printStackTrace();
                //Hata alirsa bir sonraki activity icin dene
                this.markActivityAsSent(activity, activityHome);
            }
        }

        return null;
    }
    
    private void markActivityAsSent(Activity activity, ActivityHome activityHome){
    	activity.setDueDateOverEmailSent(true);
        activityHome.setInstance(activity);
        activityHome.persist();
    }

    public static String getCronInterval() {
        //return "0/30 * * * * ?"; // test etmek için every 30 second
        return "0 0 * * * ?"; //EVERY HOUR
    }

    public User getMailToUser() {
        return mailToUser;
    }

    public void setMailToUser(User mailToUser) {
        this.mailToUser = mailToUser;
    }

    public Activity getActivity() {
        return activity;
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

	public ProjectTeam getProjectTeam() {
		return projectTeam;
	}

	public void setProjectTeam(ProjectTeam projectTeam) {
		this.projectTeam = projectTeam;
	}
    
}
